<template>
    <a-modal v-model:open="visible.value" title="新建提醒" @cancel="handleCancel" width="610px"
        @ok="handleOk" cancelText="取消" okText="确定" :confirmLoading="loading">

        <a-form :label-col="labelCol" :wrapper-col="wrapperCol" :model="formState" ref="formRef" :rules="rules">
            <a-form-item label="提醒任务" name="remindTask">
                <a-select  
                    v-model:value="formState.remindTask" 
                    :options="taskData" 
                    mode="multiple"
                    placeholder="选择要提醒的任务"
                    :loading="taskLoading"
                ></a-select>
            </a-form-item>
            <a-form-item label="提醒对象" name="remindUsers">
                <a-select  
                    v-model:value="formState.remindUsers" 
                    :options="userData" 
                    mode="multiple"
                    placeholder="选择要提醒的用户"
                    :loading="userLoading"
                ></a-select>
            </a-form-item>
            <a-form-item label="提醒方式" name="remindType">
                <a-radio-group v-model:value="formState.remindType" name="radioGroup">
                    <a-radio value="系统提示">系统提示</a-radio>
                    <a-radio value="邮件" disabled>邮件</a-radio>
                    <a-radio value="短信" disabled>短信</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item label="提醒留言" name="remindMessage">
                <a-textarea 
                    v-model:value="formState.remindMessage" 
                    show-count 
                    :maxlength="100"
                    :autosize="{ minRows: 4, maxRows: 4 }"
                    placeholder="输入提醒留言内容" 
                />
            </a-form-item>
        </a-form>
    </a-modal>
</template>
<script lang="ts" setup>
import { message } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import type { UnwrapRef } from 'vue';
import TaskDao from '@/daos/task_dao';
import ProjecrDao from '@/daos/project_dao';

const taskDao = new TaskDao();
const projectDao = new ProjecrDao();

interface FormState {
    remindTask: string[];
    remindUsers: string[];
    remindType: string;
    remindMessage: string;
}

const formRef = ref();
const formState: UnwrapRef<FormState> = reactive({
    remindTask: [],
    remindUsers: [],
    remindType: '系统提示',
    remindMessage: ''
});

const labelCol = { style: { width: '130px' } };
const wrapperCol = { span: 14 };

const props = defineProps({
    modelVisible: {
        type: Boolean,
        default: false
    },
    projectId: {
        type: Number,
        required: true
    },
    projectType: {
        type: Number,
        required: true
    }
});

const emit = defineEmits(['update:modelVisible', 'confirm']);

const visible = computed(() => {
    return ref(props.modelVisible);
});

// 状态变量
const loading = ref(false);
const taskLoading = ref(false);
const userLoading = ref(false);
const taskData = ref([]);
const userData = ref([]);

// 表单验证规则
const rules: Record<string, Rule[]> = {
    remindTask: [
        { required: true, message: '请选择提醒任务', type: 'array' }
    ],
    remindUsers: [
        { required: true, message: '请选择提醒对象', type: 'array' }
    ],
    remindMessage: [
        { required: true, message: '请输入提醒留言内容', trigger: 'blur' }
    ]
};

// 加载任务数据
const loadTaskData = async () => {
    taskLoading.value = true;
    try {
        // 使用正确的方法加载任务数据 - findTasksByProjectId需要多个参数
        const result = await taskDao.findTasksByProjectId(
            props.projectId,  // 项目ID
            '',               // 任务名称，空表示不筛选
            null,             // 任务类型，null表示不筛选
            null,             // 课程ID，null表示不筛选
            null,             // 创建人ID，null表示不筛选
            null,             // 用户ID，null表示不筛选
            1,                // 当前页码
            100               // 每页数量
        );
        
        if (result.data.code === 200) {
            // 将任务数据转换为select组件需要的格式
            const tasks = result.data.data?.rows || [];
            taskData.value = tasks.map(task => ({
                label: task.taskName,
                value: task.taskId,
                disabled: false
            }));
        } else {
            message.error('加载任务数据失败');
        }
    } catch (error) {
        console.error('加载任务数据失败', error);
        taskData.value = [];
    } finally {
        taskLoading.value = false;
    }
};

// 加载用户数据
const loadUserData = async () => {
    userLoading.value = true;
    try {
        // 根据项目类型加载不同的用户数据
        const result = await projectDao.findProjectMemberByProjectId(
            props.projectId, 
            '', 
            props.projectType
        );
        if (result.data.code === 200) {
            // 将用户数据转换为select组件需要的格式
            userData.value = (result.data.data || []).map(user => ({
                label: user.userName,
                value: user.userId,
                disabled: false
            }));
        } else {
            message.error('加载用户数据失败');
        }
    } catch (error) {
        console.error('加载用户数据失败', error);
        userData.value = [];
    } finally {
        userLoading.value = false;
    }
};

// 重置表单
const resetForm = () => {
    formRef.value.resetFields();
};

// 取消按钮
const handleCancel = () => {
    resetForm();
    emit('update:modelVisible', false);
};

// 确认按钮
const handleOk = () => {
    formRef.value.validate().then(async () => {
        loading.value = true;
        try {
            // 调用API发送提醒
            const result = await projectDao.createRemind({
                projectId: props.projectId,
                taskIds: formState.remindTask,
                userIds: formState.remindUsers,
                remindType: formState.remindType,
                message: formState.remindMessage
            });
            
            if (result.data.code === 200) {
                message.success('提醒创建成功');
                emit('confirm');
                emit('update:modelVisible', false);
                resetForm();
            } else {
                message.error(result.data.message || '创建提醒失败');
            }
        } catch (error) {
            console.error('创建提醒失败', error);
            message.error('创建提醒失败，请重试');
        } finally {
            loading.value = false;
        }
    }).catch(error => {
        console.log('表单验证失败:', error);
    });
};

// 当模态框打开时加载数据
watch(() => props.modelVisible, (newVal) => {
    if (newVal) {
        loadTaskData();
        loadUserData();
    }
});

// 组件挂载时初始化
onMounted(() => {
    if (props.modelVisible) {
        loadTaskData();
        loadUserData();
    }
});
</script>
